<template>
  <div class="goods-item">
    <img v-lazy="showImage" :alt="good.title" @load="imageLoad" @click="itemClick" />
    <div class="goods-info">
      <p>{{good.title}}</p>
      <span class="price">{{good.price}}</span>
      <!-- 收藏数 -->
      <span class="collect">{{good.cfav}}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name: "GoodsItem",
    props: {
      good: {
        type: Object,
        default: () => {}
      }
    },
    methods: {
      imageLoad() {
        // 发送事件到事件总线
        // this.$bus 是一个Vue实例, 可以作为事件总线
        if (this.$route.path.indexOf('/home') >= 0) {
          this.$bus.$emit('home-goods-item-image-load');
        } else if (this.$route.path.indexOf('/detail') >= 0) {
          this.$bus.$emit('detail-goods-item-image-load');
        }
      },
      itemClick() {
        if (this.$route.path.indexOf('/detail') >= 0) {
          // 推荐的数据后端大多不支持
          // 强制刷新组件
          // this.$forceUpdate();
        } else {
          const iid = this.good.iid || this.good.item_id;
          this.$router.push('/detail/' + iid);
        }
      }
    },
    computed: {
      showImage() {
        return this.good.image || this.good.show.img;
      }
    }
  }
</script>

<style scoped>
  .goods-item {
    padding-bottom: 40px;
    position: relative;

    width: 48%;
  }

  .goods-item img {
    width: 100%;
    border-radius: 5px;
  }

  .goods-info {
    font-size: 12px;
    position: absolute;
    bottom: 5px;
    left: 0;
    right: 0;
    overflow: hidden;
    text-align: center;
  }

  .goods-info p {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 3px;
  }

  .goods-info .price {
    color: var(--color-high-text);
    margin-right: 20px;
  }

  .goods-info .collect {
    position: relative;
  }

  .goods-info .collect::before {
    content: '';
    position: absolute;
    left: -15px;
    top: -1px;
    width: 14px;
    height: 14px;
    background: url("~assets/img/common/collect.svg") 0 0/14px 14px;
  }
</style>
